using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;
using System.Data.SqlClient;
public partial class DentistSearchControl : System.Web.UI.UserControl
{
    // creating an instance of manager class
    Manager mgr = new Manager(true,"ConnectionString");
    string _fromPage = "";
    public string fromPage
    {
        set { _fromPage = value; }
        get { return _fromPage; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMesg.Text = "";
        if (!Page.IsPostBack)
        {
            // Used to store the doctrs id found based on the search

            FillCombos();
        }
        btnSearch.Attributes.Add("onclick", "return Dentist_checkError();");

        txtCity.Attributes.Add("onfocus", "BlankSearchFields('" + txtCity.ClientID + "', 'City :');");
        txtZipCode.Attributes.Add("onfocus", "BlankSearchFields('" + txtZipCode.ClientID + "', 'Zipcode:');");
        txtLName.Attributes.Add("onfocus", "BlankSearchFields('" + txtLName.ClientID + "', 'Last Name:');");

        txtCity.Attributes.Add("onblur", "FillSearchFields('" + txtCity.ClientID + "', 'City :');");
        txtZipCode.Attributes.Add("onblur", "FillSearchFields('" + txtZipCode.ClientID + "', 'Zipcode:');");
        txtLName.Attributes.Add("onblur", "FillSearchFields('" + txtLName.ClientID + "', 'Last Name:');");
    }

    /// <summary>
    /// Fill all the combos on the page with default values from database.
    /// </summary>
    private void FillCombos()
    {
        //filling the dropdown list boxes        
        //mgr.BindList("select id,specialty from tbl_DentistSpecialty order by specialty", "specialty", "Id", ddlSpeciality, "");
        //mgr.BindList("select stateid,name from tbl_states order by name", "Name", "StateId", ddlState, "State :");
        mgr.BindList("select [countryname],countrycode from tbl_country where(countrycode='US')OR (countrycode='CA') order by [countryname]", "countryname", "countrycode", ddlCountry, "Country");
        mgr.BindList("select id,specialty from tbl_DentistSubSpecialty order by specialty", "specialty", "Id", ddlSubSpeciality, "Subspecialty :");

        // COMMENTED BY DEEPAK AFTER DISCUSSION WITH KAJAL -- NO UNION REQUIRED AS THERE ARE ONLY CATEGORY & SUBCATEGORY FOR DENTIST
        // DATE: 12TH FEB 2008
        //mgr.BindList("select cast(id as varchar)+',0' as c,specialty from tbl_DentistSpecialty union select '0,' + cast(id as varchar) as c,specialty from tbl_DentistSubSpecialty order by specialty", "specialty", "c", ddlSpeciality, "Specialty");
        mgr.BindList("select id as c, specialty from tbl_DentistSpecialty order by specialty", "specialty", "c", ddlSpeciality, "Specialty");
        // COMMENTS END

       // ddlSpeciality.Items.Insert(0, new ListItem("Select", "0,0"));
        ddlState.Items.Insert(0, new ListItem("State/Province", "0"));

        //Filling the Ratings Combos
        string strText = "";
        for (int i = 101; i >= 69; i--)
        {
            if (i == 101)
            {
                ddlRating.Items.Add(new ListItem("All Ratings", "0"));
            }
            else
            {
                strText = i.ToString();
                if (i < 100)
                    strText = i.ToString(); // +" & Above";
                if (i == 69)
                {
                    strText = " All ";
                   //ddlRating.Items.Add(new ListItem(strText, "0"));
                }
                else
                    ddlRating.Items.Add(new ListItem(strText, i.ToString()));
            }
        }

    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Session["Speciality"] = "";
        string qstring = "";

        if (ddlSpeciality.Items.Count > 1)
        {
            if (ddlSpeciality.SelectedIndex > 0)
            {
                // Commented at 210808 by ranjeet
                //Session["Speciality"] = ddlSpeciality.SelectedItem.Text.Trim().Replace(" ", "_");
                //qstring = "?specialty=" + Session["Speciality"];
                //end

                //added
                Session["Speciality"] = ddlSpeciality.SelectedItem.Text.Trim().Replace(" ", "_");
                qstring = Session["Speciality"].ToString();
                //end
            }
        }

        if (ddlState.Items.Count > 1)
        {
            if (ddlState.SelectedIndex > 0)
            {
                //Commenete at 210808

                //if (qstring == "")
                //    qstring = "?state=" + ddlState.SelectedItem.Text.Trim().Replace(" ", "_");
                //else
                //    qstring = qstring + "&state=" + ddlState.SelectedItem.Text.Trim().Replace(" ", "_");

                //End commented

                //Added

                if (qstring == "")
                    qstring = ddlState.SelectedItem.Text.Trim().Replace(" ", "_");
                else
                    qstring = qstring + "/" + ddlState.SelectedItem.Text.Trim().Replace(" ", "_");

                //End
            }
        }


        if (txtCity.Text.Trim().Equals("City :") || txtCity.Text.Trim() == "")
            txtCity.Text = "";
        else if (qstring == "")
        {
            //qstring = "?city=" + txtCity.Text.Trim().Replace(" ", "_");
            qstring = txtCity.Text.Trim().Replace(" ", "_");
        }
        else
        {
            //qstring = qstring + "&city=" + txtCity.Text.Trim().Replace(" ", "_");
            qstring = qstring + "/" + txtCity.Text.Trim().Replace(" ", "_");
        }



        if (txtZipCode.Text.Trim().Equals("Zipcode:") || txtZipCode.Text.Trim() == "")
            txtZipCode.Text = "";
        else if (qstring == "")
        {
            //qstring = "?zip=" + txtZipCode.Text.Trim().Replace(" ", "_");
            qstring = txtZipCode.Text.Trim().Replace(" ", "_");

        }
        else
        {
            //qstring = qstring + "&zip=" + txtZipCode.Text.Replace(" ", "_");
            qstring = qstring + "/" + txtZipCode.Text.Replace(" ", "_");

        }


        //Commented at 210808 by ranjeet to URL rewriting for dentst search

        //if (ddlSubSpeciality.Items.Count > 1)
        //{
        //    if (ddlSubSpeciality.SelectedIndex > 0)
        //    {
        //        if (qstring == "")
        //            qstring = "?Subspecialty=" + ddlSubSpeciality.SelectedItem.Text.Trim().Replace(" ", "_");
        //        else
        //            qstring = qstring + "&Subspecialty=" + ddlSubSpeciality.SelectedItem.Text.Trim().Replace(" ", "_");
        //    }
        //}

        //End

        

        if (txtLName.Text.Trim().Equals("Last Name:"))
            txtLName.Text = "";

        

        Session["sDentistsId"] = "";
        Session["PreDoctorsId"] = "";
        Session["EnFeaDoctorsId"] = "";
        Session["StdFeaDoctorsId"] = "";
        Session["Travel_Dis"] = "";
        Session["Top3"] = "";
        Session["ZipCode"] = "";
        Session["City"] = "";
        Session["State"] = "";
        Session["FteaturedDentistsId"] = "";

        // 11th Dec change to diffrentiate between dentist and doctor search by using diffrent session var

        Session["sDentistId"] = ""; // DoctorsNonFeaIds;
        Session["PreDentistId"] = ""; // PremiumDoctorsFeaturedIds;
        Session["EnDentistId"] = ""; // EnhancedDoctorsFeaturedIds;
        Session["StdDentistId"] = ""; // StandardDoctorsFeaturedIds;

        // 11th dec Changes End

        #region calling stored procedure
        // get the search results
        string[] strSpID = ddlSpeciality.SelectedValue.Split(',');
        //Response.Write (strSpID[0] + "|" + strSpID[1]);
        //Response.End();
        try
        {
            //SqlParameter[] sqlParam = new SqlParameter[9];
            //sqlParam[0] = new SqlParameter("@state", SqlDbType.VarChar, 2);
            //sqlParam[1] = new SqlParameter("@city", SqlDbType.VarChar, 50);
            //sqlParam[2] = new SqlParameter("@zip", SqlDbType.VarChar, 10);
            //sqlParam[3] = new SqlParameter("@spec_id", SqlDbType.Int);
            //sqlParam[4] = new SqlParameter("@rating", SqlDbType.Int);
            //sqlParam[5] = new SqlParameter("@FName", SqlDbType.VarChar, 200);
            //sqlParam[6] = new SqlParameter("@LName", SqlDbType.VarChar, 200);
            //sqlParam[7] = new SqlParameter("@subspec_id", SqlDbType.Int);

            SqlParameter[] sqlParam = new SqlParameter[9];
            sqlParam[0] = new SqlParameter("@state", SqlDbType.VarChar, 2);
            sqlParam[1] = new SqlParameter("@city", SqlDbType.VarChar, 50);
            sqlParam[2] = new SqlParameter("@zip", SqlDbType.VarChar, 10);
            sqlParam[3] = new SqlParameter("@SpecialtyID", SqlDbType.Int);
            sqlParam[4] = new SqlParameter("@Rate", SqlDbType.Int);
            sqlParam[5] = new SqlParameter("@FirstName", SqlDbType.VarChar, 200);
            sqlParam[6] = new SqlParameter("@LastName", SqlDbType.VarChar, 200);
            sqlParam[7] = new SqlParameter("@SubSpecialtyID", SqlDbType.Int);

            //Added for implementing the distance Search
            //sqlParam[8] = new SqlParameter("@Travel_Dis", SqlDbType.Float);
            sqlParam[8] = new SqlParameter("@TravelDistance", SqlDbType.Float);

            //

            sqlParam[0].Value = ddlState.SelectedItem.Value.Equals("0") ? "" : ddlState.SelectedItem.Value;
            sqlParam[1].Value = txtCity.Text.Trim();
            sqlParam[2].Value = txtZipCode.Text.Trim();
            sqlParam[3].Value = strSpID[0]; // ddlSpeciality.SelectedItem.Value;
            sqlParam[4].Value = ddlRating.SelectedItem.Value;
            sqlParam[5].Value = "";
            sqlParam[6].Value = txtLName.Text.Trim();
            sqlParam[7].Value = ddlSubSpeciality.SelectedItem.Value;
            sqlParam[8].Value = ddlDistance.SelectedItem.Value;
           
          //DataSet ds_result = mgr.ExecuteQuery("DentistSearch_HomePage", sqlParam, "tbl_srch");
            DataSet ds_result = mgr.ExecuteQuery("HomepageDentSearch", sqlParam, "tbl_srch");


            // tables[0] contains non-featured 
            // tables[1] contains Premium  featured Doctor  
            // tables[2] contains Enhanced  featured Doctor 
            // tables3] contains Standard  featured Doctor 
            string DoctorsNonFeaIds = GetDentistId(ds_result);
            string PremiumDoctorsFeaturedIds = GetPremiumDentistsIdFeat(ds_result, 1);
            string EnhancedDoctorsFeaturedIds = GetEnhancedDentistsIdFeat(ds_result, 1);
            string StandardDoctorsFeaturedIds = GetStandardDentistsIdFeat(ds_result, 1);
            // get top 3
            string Top3DrFeaturedIds = GetPremiumDentistsIdFeat(ds_result, 1);

            if ((DoctorsNonFeaIds.Trim().Length > 0) || (PremiumDoctorsFeaturedIds.Trim().Length > 0) || (Top3DrFeaturedIds.Trim().Length > 0) || (EnhancedDoctorsFeaturedIds.Trim().Length > 0) || (StandardDoctorsFeaturedIds.Trim().Length > 0))
            {
                //Session["sDoctorsId"] = DoctorsNonFeaIds;
                //Session["PreDoctorsId"] = PremiumDoctorsFeaturedIds;
                //Session["EnFeaDoctorsId"] = EnhancedDoctorsFeaturedIds;
                //Session["StdFeaDoctorsId"] = StandardDoctorsFeaturedIds;
                Session["Top3"] = Top3DrFeaturedIds;
                Session["pageFromOrAction"] = "home";

                // 8th March
                Session["PreviousSpeciality"] = "";
                Session["PreviousSubSpeciality"] = "";

                if (ddlSpeciality.SelectedIndex > 0)
                    Session["PreviousSpeciality"] = ddlSpeciality.SelectedItem.Text;
                if (ddlSubSpeciality.SelectedIndex > 0)
                    Session["PreviousSubSpeciality"] = ddlSubSpeciality.SelectedItem.Text;
                //
                
                // 11th Dec

                Session["sDentistId"] = DoctorsNonFeaIds; // DoctorsNonFeaIds;
                Session["PreDentistId"] = PremiumDoctorsFeaturedIds; // PremiumDoctorsFeaturedIds;
                Session["EnDentistId"] = EnhancedDoctorsFeaturedIds; // EnhancedDoctorsFeaturedIds;
                Session["StdDentistId"] = StandardDoctorsFeaturedIds; // StandardDoctorsFeaturedIds;
                Session["FteaturedDentistsId"] = PremiumDoctorsFeaturedIds + EnhancedDoctorsFeaturedIds + StandardDoctorsFeaturedIds;
                // 11th Dec changes end
                if (ddlDistance.SelectedItem.Value.Trim() != "0") // to implement Distance Search Functionality
                {
                   // Session["ZipCode"] = txtCity.Text.Trim();
                   // Session["City"] = txtCity.Text.Trim();
                   // Session["Travel_Dis"] = ddlDistance.SelectedItem.Value.Trim();
                   //// Session["State"] = ddlState.SelectedItem.Value.Trim();
                   // Response.Write("Session[Travel_Dis]: " + Session["Travel_Dis"]);

                    Session["ZipCode"] = txtZipCode.Text.Trim();
                    Session["City"] = txtCity.Text.Trim();
                    Session["Travel_Dis"] = ddlDistance.SelectedItem.Value.Trim();
                    Session["State"] = ddlState.SelectedItem.Value.Trim();
                    //     Response.Write("Session[Travel_Dis]: " + Session["Travel_Dis"]);

                }
          //      Response.Redirect("SearchResults_dentist.aspx", true);

                //int i;
                //for (i = 0; i < 9; i++)
                //{
                //    Response.Write(sqlParam[i].ToString() + ": " + sqlParam[i].Value + "<BR>");
                //}

                qstring = qstring.ToString().Trim().Replace("(", "_");
                qstring = qstring.ToString().Trim().Replace(")", "_");
                qstring = qstring.ToString().Trim().Replace("_&_", "_");
                qstring = qstring.ToString().Trim().Replace("[", "_");
                qstring = qstring.ToString().Trim().Replace("]", "_");
                qstring = qstring.ToString().Trim().Replace("\\", "_");
                qstring = qstring.ToString().Trim().Replace("//", "_");
                qstring = qstring.ToString().Trim().Replace("-", "_");
                qstring = qstring.ToString().Trim().Replace("___", "_"); 
                qstring = qstring.ToString().Trim().Replace("__", "_");

                //Commented at 210808 by ranjeet

                //Response.Redirect("SearchResultsDent.aspx" + qstring.ToString().Trim(), true);

                //End

                if (qstring != "")
                {
                    if (this._fromPage == "CommunityPage")
                    {
                        Response.Redirect(Session["strHttp"] + "SearchResultDenCom.aspx", false);
                    }
                    else
                    {
                        Response.Redirect(qstring.ToString().Trim() + "/dentist.aspx", true);
                    }
                }
                else
                {
                    Response.Redirect("search" + "/dentist.aspx", true);
                }
            }
            else
            {
                lblMesg.Text = "No records found based on the criteria specified. Please try again.";
                lblMesg.ForeColor = System.Drawing.Color.Red;
                lblMesg.Font.Bold = true;
                Session["NoDenResult"] = "true";
            }
        }
        catch (Exception)
        {
            lblMesg.Visible = true;
            lblMesg.Text = "An error occured while processing request.";
            lblMesg.ForeColor = System.Drawing.Color.Red;
        }

        #endregion

    }


    /// <summary>
    /// Get the doctorsids of non-featured doctors into a string
    /// </summary>
    /// <param name="ds"></param>
    /// <returns></returns>

    private string GetDentistId(DataSet ds)
    {
        string DentistIds = "";
        try
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (i == 0)
                    { DentistIds = ds.Tables[0].Rows[i][0].ToString(); }
                    else
                    { DentistIds += "," + ds.Tables[0].Rows[i][0].ToString(); }
                }
            }
        }
        catch
        {
            DentistIds = "";
        }
        return DentistIds;
    }


    /// <summary>
    /// get featured dr id s j=2 means get top 3
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="j"></param>
    /// <returns></returns>
    private string GetPremiumDentistsIdFeat(DataSet ds, int j)
    {
        string DentistsIds = "";
        int count = 0;
        int k = 0;
        try
        {
            if (ds.Tables[1].Rows.Count > 0)
            {
                if (j == 2)
                {
                    if (ds.Tables[1].Rows.Count > 3)
                    {
                        count = 3;
                    }
                    else
                    {
                        count = ds.Tables[1].Rows.Count;
                    }

                    k = 0;
                }
                else
                {
                    count = ds.Tables[1].Rows.Count;
                    //    k = 3;
                }
                //ds.Tables[1].Rows.Count
                for (int i = k; i < count; i++)
                {
                    if ((i == 0) || (i == 3))
                    {
                        DentistsIds = ds.Tables[1].Rows[i][0].ToString();
                    }
                    else
                    {
                        DentistsIds += "," + ds.Tables[1].Rows[i][0].ToString();
                    }
                }
            }
        }
        catch
        {
            DentistsIds = "";
        }

        return DentistsIds;


    }
    private string GetEnhancedDentistsIdFeat(DataSet ds, int j)
    {
        string DoctorsIds = "";

        try
        {

            // DataSet ds = mgr.ExecuteQuery(sql, "tblResults");
            if (ds.Tables[2].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[2].Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        DoctorsIds = ds.Tables[2].Rows[i][0].ToString();
                    }
                    else
                    {
                        DoctorsIds += "," + ds.Tables[2].Rows[i][0].ToString();
                    }
                }
            }
        }


        catch
        {
            DoctorsIds = "";
        }

        return DoctorsIds;


    }
    private string GetStandardDentistsIdFeat(DataSet ds, int j)
    {
        string DoctorsIds = "";

        try
        {

            // DataSet ds = mgr.ExecuteQuery(sql, "tblResults");
            if (ds.Tables[3].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[3].Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        DoctorsIds = ds.Tables[3].Rows[i][0].ToString();
                    }
                    else
                    {
                        DoctorsIds += "," + ds.Tables[3].Rows[i][0].ToString();
                    }
                }
            }
        }


        catch
        {
            DoctorsIds = "";
        }

        return DoctorsIds;


    }
    protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
    {
        string countryID = ddlCountry.SelectedValue;
        // mgr.BindList("select countrycode,countryname from tbl_country", "countryname", "countrycode", ddlCountry, "select");
        mgr.BindList("select stateid,name from tbl_states where CountryID='" + countryID + "'  order by name", "Name", "StateId", ddlState, "select");
        if (ddlCountry.SelectedValue == "US")
        {
            ddlState.Items.Insert(0, new ListItem("Select a State", "0"));
        }
        else
        {
            ddlState.Items.Insert(0, new ListItem("Select a Province", "0"));
        }
    }
   
}
